# -*- coding: utf-8 -*-
from typing import List

from app.features.enum.edata_type import EDataType as DataType
from app.features.service.field_info import FieldInfo


class SheetInfo:
    """
    将一张Excel表格解析成通用数据类,然后再根据通用的数据信息,导出
    """
    # 表格sheet名称
    tableName = ''
    # 表格配置参数 {string, [string]>}
    tableConfig = {}
    # 存储每个字段的信息以及按字段存储的所有数据, 下标0 开始
    _fieldInfo = []
    # 段名对应到_fieldInfo中的下标位置索引,
    # 快速找到指定字段列信息和数据(key:fieldName, value:index),但忽略array或dict的子元素列
    _indexForFieldNameToColumnSeq = {}

    def add_field(self, fieldInfo:FieldInfo):
        """
        增加excel中表格的列的信息存储 SheetInfo 信息中
        """
        # 增加列表
        self._fieldInfo.append(fieldInfo)
        # 设置快速查找dict
        self._indexForFieldNameToColumnSeq[fieldInfo.fieldName] = len(self._fieldInfo) - 1

    def get_fieldInfo_by_fieldName(self, fieldName) -> FieldInfo:
        """
        通过fieldName获取FieldInfo
        """
        if fieldName in self._indexForFieldNameToColumnSeq:
            # 找到索引位置,返回索引对应的FieldInfo
            return self._fieldInfo[self._indexForFieldNameToColumnSeq[fieldName]]
        else:
            return None
    
    def get_all_fieldInfo(self) -> List[FieldInfo]:
        """
        通过fieldName获取FieldInfo
        """
        return self._fieldInfo
    
    def get_keyColumn_fieldInfo(self) -> FieldInfo:
        """
        返回第一个主键列fieldInfo
        """
        if len(self._fieldInfo) > 0:
            return self._fieldInfo[0]
        else:
            return None

    # 获取依次排列的表格中各字段信息,但无视array、dict型的嵌套结构,将其下属子元素作为独立字段
    def GetAllClientFieldInfoIgnoreSetDataStructure(self):
        allFieldInfo = []
        for fieldInfo in self._fieldInfo:
            self._AddClientFieldInfoFromOneField(self, fieldInfo, allFieldInfo);

        return allFieldInfo

    # 逐个
    def _AddClientFieldInfoFromOneField(self, fieldInfo:FieldInfo, allFieldInfo:List[FieldInfo]):
        if  fieldInfo.DataType == DataType.Array or fieldInfo.DataType == DataType.Dict:
            allFieldInfo.append(fieldInfo)
            for childField in fieldInfo.ChildField:
                self._AddClientFieldInfoFromOneField(self, childField, allFieldInfo)
        elif fieldInfo.IsIgnoreClientExport == False:
            allFieldInfo.append(fieldInfo)
